package com.next

import grails.transaction.Transactional
import org.springframework.security.access.annotation.Secured

import static org.springframework.http.HttpStatus.*

@Secured(['ROLE_ADMINISTRATOR', 'ROLE_COMPANY_ADMINISTRATOR', 'ROLE_COMPANY_USER'])
@Transactional(readOnly = true)
class AssetTeamController
{

    static allowedMethods = [save: "POST", update: "PUT", delete: "DELETE"]

    def springSecurityService
    def exportService

    def index(Integer max)
    {
        def username = springSecurityService?.getPrincipal()?.username
        def assetTeamList = AssetTeam.findAll("from AssetTeam where user.username = '${username}' order by modifiedDate desc", [max: params.max ?: 10, offset: params.offset ?: 0])
        def count = AssetTeam.executeQuery("select count(id) from AssetTeam where user.username = '${username}'")

        respond assetTeamList, model: [assetTeamCount: count[0], params: params]
    }

    def show(AssetTeam assetTeam)
    {
        respond assetTeam
    }

    def create()
    {
        def asset = Asset.findById(params['asset'])
        def username = springSecurityService.getPrincipal().username
        def user = User.findByUsername(username)
        if (asset?.user == user || UserRole.findByUserAndRole(user, Role.findByAuthority("ROLE_ADMINISTRATOR")))
        {
            def userList = User.list()
            def assetTeams = AssetTeam.findAllByAsset(asset)
            assetTeams?.each {
                userList -= it?.user
            }
            respond new AssetTeam(params), model: [userList: userList]
        }
        else
        {
            flash.message = message(code: 'opportunity.edit.permission.denied')
            redirect(controller: "asset", action: "show", params: [id: asset.id])
            return
        }
    }

    @Transactional
    def save(AssetTeam assetTeam)
    {
        if (assetTeam == null)
        {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        if (assetTeam.hasErrors())
        {
            transactionStatus.setRollbackOnly()
            respond assetTeam.errors, view: 'create'
            return
        }

        assetTeam.save flush: true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.created.message', args: [message(code: 'assetTeam.label', default: 'AssetTeam'), assetTeam.id])
                redirect(controller: 'asset', action: 'show', params: [id: assetTeam?.asset?.id])
            }
            '*' { respond assetTeam, [status: CREATED] }
        }
    }

    def edit(AssetTeam assetTeam)
    {
        respond assetTeam
    }

    @Transactional
    def update(AssetTeam assetTeam)
    {
        if (assetTeam == null)
        {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        if (assetTeam.hasErrors())
        {
            transactionStatus.setRollbackOnly()
            respond assetTeam.errors, view: 'edit'
            return
        }

        assetTeam.save flush: true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.updated.message', args: [message(code: 'assetTeam.label', default: 'AssetTeam'), assetTeam.id])
                redirect assetTeam
            }
            '*' { respond assetTeam, [status: OK] }
        }
    }

    @Transactional
    def delete(AssetTeam assetTeam)
    {

        if (assetTeam == null)
        {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        assetTeam.delete flush: true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.deleted.message', args: [message(code: 'assetTeam.label', default: 'AssetTeam'), assetTeam.id])
                redirect(controller: 'asset', action: 'show', params: [id: assetTeam?.asset?.id])
            }
            '*' { render status: NO_CONTENT }
        }
    }

    protected void notFound()
    {
        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.not.found.message', args: [message(code: 'assetTeam.label', default: 'AssetTeam'), params.id])
                redirect action: "index", method: "GET"
            }
            '*' { render status: NOT_FOUND }
        }
    }

    def searchAssetTeam()
    {
        def username = springSecurityService?.getPrincipal()?.username
        String name = params["name"]

        String sql = "from AssetTeam as u where u.user.username = '${username}'"
        if (name)
        {
            sql += " and u.asset.name like '%${name}%'"
        }

        def ownerFullName = params['ownerFullName']
        if (ownerFullName)
        {
            sql += " and u.asset.user.fullName like '%${ownerFullName}%'"
        }

        def accountName = params['accountName']
        if (accountName)
        {
            sql += " and u.asset.account.name like '%${accountName}%'"
        }

        String countSql = "select count(u.id) " + sql
        sql += " order by u.modifiedDate desc"

        def list = AssetTeam.findAll(sql, [max: params.max ?: 10, offset: params.offset ?: 0])
        def count = AssetTeam.executeQuery(countSql)

        respond list, model: [assetTeamCount: count[0], params: params], view: 'index'
    }

    def exportAssetTeam()
    {
        def username = springSecurityService?.getPrincipal()?.username
        String name = params["name"]

        String sql = "from AssetTeam as u where u.user.username = '${username}'"
        if (name)
        {
            sql += " and u.asset.name like '%${name}%'"
        }

        def ownerFullName = params['ownerFullName']
        if (ownerFullName)
        {
            sql += " and u.asset.user.fullName like '%${ownerFullName}%'"
        }

        def accountName = params['accountName']
        if (accountName)
        {
            sql += " and u.asset.account.name like '%${accountName}%'"
        }

        String countSql = "select count(u.id) " + sql
        sql += " order by u.modifiedDate desc"

        def list = AssetTeam.findAll(sql)
        def count = AssetTeam.executeQuery(countSql)

        if (params?.f && params.f != "html")
        {
            response.contentType = grailsApplication.config.grails.mime.types[params.f]
            response.setHeader("Content-disposition", "attachment; filename=assetTeam.${params.extension}")
            List fields = ["asset.name", "asset.code", "asset.status.name", "asset.product.name", "asset.account.name", "asset.contact.fullName", "asset.quantity", "asset.purchaseDate", "asset.installDate", "asset.usageEndDate", "asset.competitorAsset", "asset.description", "asset.createdDate", "asset.modifiedDate"]
            Map labels = ["asset.name": "资产名称", "asset.code": "序列号", "asset.status.name": "资产状态", "asset.product.name": "产品", "asset.account.name": "客户", "asset.contact.fullName": "联系人", "asset.quantity": "数量", "asset.purchaseDate": "采购时间", "asset.installDate": "安装时间", "asset.usageEndDate": "停用时间", "asset.competitorAsset": "竞争对手的设备", "asset.description": "备注", "asset.createdDate": "创建时间", "asset.modifiedDate": "修改时间"]
            exportService.export(params.f, response.outputStream, list, fields, labels, [:], [:])
        }
    }
}
